import React, { useEffect, useState } from 'react';
import './style.scss';
import { Button, NavBar, Toast } from 'antd-mobile';
import { useNavigate } from 'react-router-dom';
import { client } from '@/utils/oss';

interface ListItemType {
  user_id: string;
  message: string;
  user_avatar: string;
  server_id: string;
  server_avatar: string;
  dir: number;
  type: string;
}
const user_id = '1';
const server_id = '45629082';
// 声明一个全局变量wss
let wss: WebSocket | null = null;
const Chat: React.FC = () => {
  const [list, setList] = useState<ListItemType[]>([]);
  const [value, setValue] = useState('');
  const navigate = useNavigate();
  const handleSend = async ({ type, message }) => {
    if (message.trim() === '') return Toast.show('不能发送空消息');
    if (wss) {
      wss.send(
        JSON.stringify({
          type: 'addMessage',
          data: {
            type: type,
            message: message,
            user_id,
            server_id,
          },
        })
      );
    }
  };
  const handleChoose = () => {
    const input = document.createElement('input');
    input.type = 'file';
    input.click();

    input.addEventListener('change', async () => {
      if (input.files) {
        const file = input.files[0];
        if (!(file.type.includes('image') || file.type.includes('video'))) {
          Toast.show('只能发送图片或视频');
          return;
        }

        try {
          const resp = await client.put(file.name, file);
          // file: text | image | video
          const type = file.type.includes('image') ? 'image' : 'video';
          handleSend({ type: type, message: resp.url });
        } catch (error) {
          console.log('上传文件失败', error);
        }
      }
    });
  };
  const init = () => {
    const ws = new WebSocket(
      `ws://124.221.74.149:8003/koa/ws?user_id=${user_id}&server_id=${server_id}`
    );

    ws.addEventListener('open', () => {
      console.log('服务器建立链接');
      ws.addEventListener('message', (e) => {
        const { type, data } = JSON.parse(e.data);
        console.log('服务器消息：', data);
        if (type === 'getChatList') {
          setList(data);
        }

        if (type === 'addMessage') {
          setList((list) => list.concat(data));
        }
      });

      // 获取聊天记录
      ws.send(
        JSON.stringify({
          type: 'getChatList',
        })
      );
    });

    wss = ws;
  };

  useEffect(() => {
    document.documentElement.scrollTop = 10000;
  }, [list]);

  useEffect(() => {
    init();
  }, []);
  return (
    <div className="chat">
      <div className="header">
        <span></span>
        <span>客服</span>
      </div>
      <div className="content">
        {list.map((v, i) => {
          // v.dir  1 user   2 server
          // 根据消息方向，设置不同的样式
          const myClassName = v.dir === 1 ? 'content-right' : 'content-left';
          // 根据消息方向，设置不同的头像
          const avatar = v.dir === 1 ? v.user_avatar : v.server_avatar;
          return (
            <div className={myClassName} key={i}>
              <div className="avatar">
                <img src={avatar} alt="" />
              </div>
              <div className="content-box">
                {v.type === 'text' && (
                  <div className="content-message">{v.message}</div>
                )}
                {v.type === 'image' && (
                  <img className="img" src={v.message} alt="" />
                )}
                {v.type === 'video' && (
                  <video src={v.message} className="img" controls></video>
                )}
              </div>
            </div>
          );
        })}
      </div>

      <div className="footer">
        {/* 受控组件 */}
        <input
          className="text"
          value={value}
          onChange={(e) => setValue(e.target.value)}
          onKeyDown={(e) =>
            e.keyCode === 13 && handleSend({ type: 'text', message: value })
          }
        ></input>
        <Button
          color="primary"
          className="send"
          onClick={() => handleSend({ type: 'text', message: value })}
        >
          发送
        </Button>
        <Button color="success" onClick={() => handleChoose()}>
          媒体
        </Button>
      </div>
    </div>
  );
};

export default Chat;
